#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import re
import bz2


class Util:

    @staticmethod
    def oIterate(iteratable, orderRef):
        # iterate iteratable in the order defined by orderRef
        for x in orderRef:
            if x in iteratable:
                yield x

    @staticmethod
    def dictPut(td, key, defaultValue):
        if key not in td:
            td[key] = defaultValue
        return td[key]

    @staticmethod
    def listRemoveIf(tl, filterFunc):
        bFound = False
        for i in reversed(range(0, len(tl))):
            if filterFunc(tl[i]):
                tl.pop(i)
                bFound = True
        return bFound

    @staticmethod
    def pathCompare(path1, path2):
        # Change double slashes to slash
        path1 = re.sub(r"//", r"/", path1)
        path2 = re.sub(r"//", r"/", path2)
        # Removing ending slash
        path1 = re.sub("/$", "", path1)
        path2 = re.sub("/$", "", path2)

        if path1 == path2:
            return 1
        return 0

    @staticmethod
    def isInstanceList(obj, *instances):
        for inst in instances:
            if isinstance(obj, inst):
                return True
        return False

    @staticmethod
    def pamGetModuleTypesProvided(pamModuleName):
        # read information from man pages
        # eg: read information from "/usr/share/man/man8/pam_securetty.8.bz2" for PAM module "pam_securetty.so"

        # sucks: no man page
        if pamModuleName == "pam_gnome_keyring.so":
            return ["password"]
        if pamModuleName == "pam_cracklib.so":
            return ["password"]

        # normal process
        try:
            manFile = os.path.join("/usr/share/man/man8", pamModuleName.replace(".so", ".8.bz2"))
            with bz2.open(manFile, "rt") as f:
                ret = []
                bFlag = False
                for line in f.read().split("\n"):
                    if not bFlag:
                        if re.fullmatch(r'\.SH "MODULE TYPES? PROVIDED"', line):    # chapter entered
                            bFlag = True
                    else:
                        if line.startswith(".SH "):                                 # next chapter
                            break
                        ret += [x.group(1) for x in re.finditer(r'\\fB(.*?)\\fR', line)]
                        ret += [x.group(1) for x in re.finditer(r'\\fI(.*?)\\fR', line)]
                return ret
        except FileNotFoundError:
            return None
